import fs from "fs"
const dirpath = "plugins/js-box-plugin/config/data/user";//文件夹路径
var Template = { "listen": false };  //创建对象
let filename = `sleep.json`;//文件名

//读写群组数据
async function sleeping(id, json, save) {
    if (!save) {
       if (!fs.existsSync(dirpath)) {//如果文件夹不存在
       fs.mkdirSync(dirpath);//创建文件夹
       }
       if (!fs.existsSync(dirpath + "/" + filename)) {//如果文件不存在
       fs.writeFileSync(dirpath + "/" + filename, JSON.stringify({
       })); //创建文件
       }
       var json = JSON.parse(fs.readFileSync(dirpath + "/" + filename, "utf8"));//读取文件
       if (!json.hasOwnProperty(id)) {//如果json中不存在该用户
       json[id] = Template
       }
       if (!json[id].local_gailv) { json[id].local_gailv = Template.gailv }
       if (!json[id].gailv) { json[id].gailv = Template.local_gailv }
       return json;
       } else {
       fs.writeFileSync(dirpath + "/" + filename, JSON.stringify(json, null, "\t"));//写入文件
       return json;
    }
}

//读写个体数据
async function shield(id, json, filename, Template, save) {
    if (filename.indexOf(".json") == -1) {//如果文件名不包含.json
       filename = filename + ".json";//添加.json
     }
    if (!save) {
       if (!fs.existsSync(dirpath)) {//如果文件夹不存在
       fs.mkdirSync(dirpath);//创建文件夹
       }
       if (!fs.existsSync(dirpath + "/" + filename)) {//如果文件不存在
       fs.writeFileSync(dirpath + "/" + filename, JSON.stringify({
       }));
       }
       var json = JSON.parse(fs.readFileSync(dirpath + "/" + filename, "utf8"));
       if (!json.hasOwnProperty(id)) {//如果json中不存在该用户
        json[id] = Template
        }
        } else {
        fs.writeFileSync(dirpath + "/" + filename, JSON.stringify(json, null, "\t"));//写入文件
        return json;
    }
    return json;
}

//获取个体信息
async function people(e, keys, id) {
  let memberMap = await e.group.getMemberMap();
  let arrMember = Array.from(memberMap.values());
   var this_one = arrMember.filter(item => {
    return item.user_id == id
   })
    var lp = this_one[0]
    if (keys == 'sex') {
    var gender = '她'
    if (lp.sex == 'male')
    gender = '他'
    return gender
     }
    if (keys == 'nickname') {
     var name = lp.nickname
      if (lp.card !== '')
       name = lp.card
       return name
      }
    }

export default { sleeping, shield, people }